<template>
  <el-drawer :title="dialogTitle" v-model="dialogVisible" size="50%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="标题" prop="title">
            <el-input v-model="formData.title" placeholder="请输入标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类" prop="categoryId">
            <el-select v-model="formData.categoryId" placeholder="请选择分类" style="width: 100%">
              <el-option
                v-for="category in categoryList"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="封面" prop="coverUrl">
        <UploadImg v-model="formData.coverUrl" :limit="1" :is-show-tip="false" />
        <div class="ml-10px text-gray-500 text-10px">推荐 180x180 图片分辨率</div>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="属性" prop="attribute">
            <el-select v-model="formData.attribute" placeholder="请选择属性" style="width: 100%">
              <el-option
                v-for="(label, value) in ATTRIBUTE_MAP"
                :key="value"
                :label="label"
                :value="Number(value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
              <el-option
                v-for="(label, value) in STATUS_MAP"
                :key="value"
                :label="label"
                :value="Number(value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="计价模式" prop="pricingMode">
            <el-radio-group v-model="formData.pricingMode" @change="onPricingModeChange">
              <el-radio
                v-for="(label, value) in PRICING_MODE_MAP"
                :key="value"
                :value="Number(value)"
                >{{ label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="计价单位" prop="unitName">
            <el-select
              v-if="formData.pricingMode === 2"
              v-model="formData.unitName"
              placeholder="请选择计价单位"
              style="width: 100%"
            >
              <el-option label="两" value="两" />
              <el-option label="克" value="克" />
              <el-option label="毫升" value="毫升" />
            </el-select>
            <el-input v-else v-model="formData.unitName" placeholder="请输入计价单位，如：份、克" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="unitValue">
            <template #label>
              <Tooltip title="计价数值" message="用于购物车每次的加减数量" />
            </template>
            <el-input-number
              v-model="formData.unitValue"
              :min="1"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="price">
            <template #label>
              <Tooltip
                v-if="formData.pricingMode === 2"
                title="单价"
                message="按重量计价时无需填写单价"
              />
              <Tooltip v-else title="单价" message="按单品计价时必须填写单价" />
            </template>
            <el-input-number
              v-model="computedPrice"
              :step="1"
              :precision="2"
              :disabled="formData.pricingMode === 2"
              controls-position="right"
              style="width: 100%"
            >
              <template #suffix>元</template>
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="minQuantity">
            <template #label>
              <Tooltip title="最小限购" message="0表示不限，少于最小限购数量则不能下单" />
            </template>
            <el-input-number
              v-model="formData.minQuantity"
              :min="0"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="maxQuantity">
            <template #label>
              <Tooltip title="最大限购" message="0表示不限，超过最大限购数量则不能下单" />
            </template>
            <el-input-number
              v-model="formData.maxQuantity"
              :min="0"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="sort">
            <template #label>
              <Tooltip title="排序" message="排序数值越小越靠前" />
            </template>
            <el-input-number
              v-model="formData.sort"
              :min="0"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标签" prop="labels">
            <el-select
              v-model="formData.labels"
              allow-create
              filterable
              multiple
              default-first-option
              :reserve-keyword="false"
              placeholder="请输入标签，如：招牌菜"
            >
              <el-option
                v-for="label in formData.labels"
                :key="label"
                :label="label"
                :value="label"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="描述" prop="description">
        <editor
          v-model="formData.description"
          mode="simple"
          height="150px"
          placeholder="请输入描述"
        />
      </el-form-item>
      <el-form-item label="其他选项" prop="options">
        <el-checkbox v-model="formData.required">必选</el-checkbox>
        <el-checkbox v-model="formData.upscale">
          <Tooltip title="高端菜" message="高端菜支持优惠券抵扣" />
        </el-checkbox>
        <el-checkbox v-model="formData.reservable">可预订</el-checkbox>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="ProductForm">
import * as CategoryApi from '@/api/dine/category/CategoryApi'
import * as ProductApi from '@/api/dine/product/ProductApi'
import { ATTRIBUTE_MAP, PRICING_MODE_MAP, STATUS_MAP } from './enums'
import { fenToYuan, yuanToFen } from '@/utils'

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref<any>({
  id: undefined,
  title: '',
  description: '',
  coverUrl: '',
  price: 0,
  categoryId: '',
  attribute: null,
  pricingMode: 1,
  unitName: '份',
  unitValue: 1,
  minQuantity: 0,
  maxQuantity: 0,
  required: false,
  upscale: false,
  reservable: true,
  status: null,
  labels: '',
  sort: 1
})

const formRules = reactive({
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  coverUrl: [{ required: true, message: '请上传封面图片', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'blur' }],
  attribute: [{ required: true, message: '请选择属性', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
  unitName: [{ required: true, message: '请输入计价单位', trigger: 'blur' }],
  unitValue: [{ required: true, message: '请输入计价数值', trigger: 'blur' }],
  pricingMode: [{ required: true, message: '请选择计价模式', trigger: 'blur' }],
  price: [
    {
      message: '请输入单价',
      trigger: ['blur', 'change'],
      validator: (_rule: any, value: any, callback: any) => {
        if (formData.value.pricingMode === 1 && (!value || value <= 0)) {
          callback(new Error('按单品计价时必须填写单价'))
        } else {
          callback()
        }
      }
    }
  ]
})

const formRef = ref()

const computedPrice = computed({
  get() {
    return Number(fenToYuan(formData.value.price))
  },
  set(value) {
    formData.value.price = yuanToFen(value)
  }
})

const categoryList = ref<any>([])

const onPricingModeChange = async (mode?: string | number | boolean): any => {
  // 切换计价模式时的处理
  if (mode === 2) {
    // 切换到按重量计价时，清空价格并设置默认单位
    formData.value.price = 0
    formData.value.unitName = '克'
  } else {
    // 切换到按单品计价时，设置默认单位
    formData.value.unitName = '份'
  }
  // 重新验证表单
  await formRef.value.validateField('price')
}

const open = async (type: string, id?: number | string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      const data = await ProductApi.getDetailById(id)
      // 根据价格判断计价模式（如果价格为0且有计价单位值，则认为是按重量计价）
      if (data.price === 0 && data.unitValue > 0) {
        data.pricingMode = 2
      } else {
        data.pricingMode = 1
      }
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
  categoryList.value = await CategoryApi.getList()
}
defineExpose({ open })

const emit = defineEmits(['success'])
const submitForm = async () => {
  if (!formRef) {
    return
  }
  try {
    const valid = await formRef.value.validate()
    if (!valid) {
      return
    }
    formLoading.value = true
    if (formType.value === 'create') {
      await ProductApi.create(formData.value)
      message.success(t('common.createSuccess'))
    } else {
      await ProductApi.updateById(formData.value)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } catch (e) {
    console.error('submit error', e)
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    title: '',
    description: '',
    coverUrl: '',
    price: 0,
    categoryId: '',
    attribute: null,
    pricingMode: 1,
    unitName: '份',
    unitValue: 1,
    minQuantity: 0,
    maxQuantity: 0,
    required: false,
    upscale: false,
    reservable: true,
    status: null,
    labels: '',
    sort: 1
  }
  formRef.value?.resetFields()
}
</script>
